package com.excemly.library.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import com.excemly.library.common.ApiResponse;
import com.excemly.library.entity.Admin;
import com.excemly.library.entity.User;
import com.excemly.library.service.AdminService;
import com.excemly.library.service.UserService;
import com.excemly.library.vo.LoginRequest;
// 添加缺失的导入语句
import org.springframework.web.bind.annotation.CrossOrigin;


import com.excemly.library.vo.RegisterRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;


/**
 * 认证控制器，处理用户和管理员的登录接口
 * 处理认证相关接口，
 * 包含 /login/user （用户登录）和 /login/admin （管理员登录）端点，
 * 调用 UserService 和 AdminService 完成认证逻辑。
 * @author 开发者
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    // 修复@CrossOrigin注解
    @PostMapping("/register")
    public ApiResponse register(@RequestBody RegisterRequest registerRequest) {
        // 修复ApiResponse.error()方法调用参数
        if (userService.existsByUsername(registerRequest.getUsername())) {
            return ApiResponse.error(400, "Username is already taken!");
        }
        
        // 修复BCryptPasswordEncoder实例化
        User newUser = new User();
        newUser.setUsername(registerRequest.getUsername());
        newUser.setPassword(registerRequest.getPassword());
        // 修复角色设置方法名
        // 修复保存用户方法
        userService.createUser(newUser);
        
        // 删除JWT服务相关内容
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("message", "User registered successfully");
        return ApiResponse.success(null, responseData);
    }

    private final UserService userService;
    private final AdminService adminService;
    // 添加JwtService到构造函数
    public AuthController(UserService userService, AdminService adminService) {
        this.userService = userService;
        this.adminService = adminService;
    }    
    // 添加密码加密验证和详细错误信息
    // 修复登录方法中的@CrossOrigin注解和错误
    @CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true", maxAge = 3600, allowedHeaders = "*")
    @PostMapping("/login")
    public ApiResponse login(@RequestBody LoginRequest loginRequest) {
        try {
            System.out.println("Received login request: " + loginRequest.getUsername());
            
            // 修复登录方法中的用户查询
            User user = userService.findByUsername(loginRequest.getUsername());
            if (user == null) {
                return ApiResponse.error(401, "Invalid username or password");
            }
            
            if (!loginRequest.getPassword().equals(user.getPassword())) {
                return ApiResponse.error(401, "Invalid username or password");
            }

            Map<String, Object> userData = new HashMap<>();
    userData.put("id", user.getId());
    userData.put("username", user.getUsername());
    
    Map<String, Object> responseData = new HashMap<>();
    responseData.put("message", "Login successful");
    responseData.put("user", userData);
    // 简单验证，不使用JWT
    String token = "simple-token-" + System.currentTimeMillis();
    responseData.put("token", token);

    return ApiResponse.success(null, responseData);
        } catch (Exception e) {
            e.printStackTrace();
return ApiResponse.error(500, "Login failed: " + e.getMessage());
        }
    }
    @GetMapping("/me")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public ApiResponse getCurrentUser() {
        // 需要实现获取当前用户信息的逻辑
        return ApiResponse.success(null, Collections.singletonMap("message", "Get current user info"));
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/login/admin")
    public ApiResponse adminLogin(@RequestBody LoginRequest loginRequest) {
        Admin admin = adminService.authenticate(loginRequest.getUsername(), loginRequest.getPassword());
        if (admin == null) {
            return ApiResponse.error(401, "Invalid admin credentials");
        }
        Map<String, Object> response = new HashMap<>();
        response.put("admin", admin);
        response.put("message", "管理员登录成功");
        return ApiResponse.success(null, response);
    }
}